<?php


namespace App\Repositories\System;

use App\Facade\AppContext;
use App\Models\BaseModel;
use App\Models\System\Group;
use App\Models\System\GroupPermission;
use App\Repositories\BaseRepository;
use App\Utils\Output;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Throwable;

class GroupRepository extends BaseRepository
{

    function simpleList()
    {
        $query = Group::query();
        return $query->select('code', 'name')->get();
    }

    function adminPager($params)
    {
        extract($params);
        $query = Group::query();

        $data = $this->queryToPager($query, $params, 'id');
        return $data;
    }

    /**
     * @param $id
     * @return Output
     */
    function allPermissions($id)
    {
        $checkedPermissionCodes = GroupPermission::query()
            ->where('group_id', '=', $id)
            ->pluck('permission_code')->toArray();
        $permissionRepository = new PermissionRepository();
        return $permissionRepository->queryAllPermission(false, $checkedPermissionCodes);
    }

    /**
     * @param $data
     * @return Output
     */
    function savePermission($data)
    {
        try {
            DB::beginTransaction();
            $id = $data['id'];
            $permissionCodes = GroupPermission::query()
                ->where('group_id', '=', $id)
                ->pluck('permission_code')
                ->toArray();
            $actions = Arr::get($data, 'actions', []);
            $permissionLogic = new PermissionRepository();
            list($addPermissionIds, $removePermissionIds) = $permissionLogic->permissionDiff($permissionCodes, $actions);
            $dataArray = [];
            foreach ($addPermissionIds as $actionId) {
                $dataArray[] = [
                    'group_id' => $id,
                    'permission_code' => $actionId
                ];
            }
            GroupPermission::query()->insert($dataArray);
            GroupPermission::query()
                ->where('group_id', '=', $id)
                ->whereIn('permission_code', $removePermissionIds)
                ->delete();

            $roleLogic = new RoleRepository();
            $group = Group::find($id);
            $roleLogic->groupPermissionUpdate($group['code'], $addPermissionIds, $removePermissionIds);
            DB::commit();
            return Output::success();
        } catch (Throwable $exception) {
            DB::rollback();
            return Output::error($exception, __('system.permission.tips.save_err'));
        }
    }

    function getModel(): BaseModel
    {
        return new Group();
    }
}